﻿// Nail framework
//
// Copyright © Frank Nagl, 2008
// admin@franknagl.de
// www.franknagl.de
//
namespace Nail
{
    using System.Drawing;
    using System.Drawing.Imaging;
    using System;

    /// <summary>
    /// Floodfills the segments of a colored image.
    /// </summary>
    public class ImageInverter
    {
        /// <summary>
        /// Inverts  the passed image.
        /// </summary>
        public void ProcessImage(Bitmap image)
        {
            // check image format
            if (image.PixelFormat != PixelFormat.Format24bppRgb)
            {
                throw new ArgumentException("Source image can be color (24 bpp) image only");
            }

            const int pixelSize = 3;
            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

            // lock source bitmap data
            BitmapData imageData = image.LockBits(
                rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            // image sizes
            //stride = imageData.Stride;
            int w = imageData.Width;
            int h = imageData.Height;
            int offset = imageData.Stride - w * pixelSize;
            
            // process image
            unsafe
            {
                byte* values = (byte*)imageData.Scan0.ToPointer();//
                // for each line
                for (int y = 0; y < h - 1; y++)
                {
                    // for each pixel in line
                    for (int x = 0; x < w; x++, /*dst += pixelSize,*/ values += pixelSize)
                    {
                        // copy pixel
                        byte r = values[RGB.R];
                        byte g = values[RGB.G];
                        byte b = values[RGB.B];
                        values[RGB.R] = (byte)(255 - r);
                        values[RGB.G] = (byte)(255 - g);
                        values[RGB.B] = (byte)(255 - b);

                        //// copy pixel
                        //*dst = *src; //  ==  dst[0] = src[0];
                        //dst[1] = src[1];
                        //dst[2] = src[2];
                        //dst[3] = src[3];
                    }
                    values += offset;
                }
            }

            // unlock destination image
            image.UnlockBits(imageData);
        }
    }
}
